package com.bookstore;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/DemoServlet07")
public class DemoServlet07 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width=100;
        int height=40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        Random random = new Random();
        graphics.setColor(Color.white);
        graphics.fillRect(0,0,width,height);
        graphics.setColor(Color.BLACK);
        graphics.drawRect(0,0,width-1,height-1);
        graphics.setFont(new Font("楷体",Font.BOLD,20));
        String captcha="";
        for (int i = 0; i < 4; i++) {
            int x=20+i*20;
            int y=20+random.nextInt(10);
            int angle=random.nextInt(60)-30;
            char c=(char)(random.nextInt(26)+'A');
            captcha+=c;
            graphics.rotate(angle*Math.PI/180,x,y);
            graphics.drawString(String.valueOf(c),x,y);
            graphics.rotate(-angle*Math.PI/180,x,y);
        }
        req.getSession().setAttribute("captcha",captcha);
        resp.setContentType("image/jpeg");
        ServletOutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image,"jpeg",outputStream);
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
